import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from users.models import User


class CreateUserSer(serializers.ModelSerializer):
    '''
    创建用户序列化器
    '''

    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(label='jwt状态保持', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'sms_code', 'mobile', 'avatar', 'sms_code', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate(self, attrs):

        # 校验手机号码
        mobile = attrs['mobile']
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('手机号码错误')


        # 校验短信验证码
        redis_conn = get_redis_connection('default')
        sms_code = attrs['sms_code']
        server_smscode = redis_conn.get('sms_%s' % mobile)
        if server_smscode is None:
            raise serializers.ValidationError('短信验证码过期')
        if sms_code != server_smscode.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):
        '''
        创建用户
        '''
        # 移除数据库中不存在的属性
        del validated_data['sms_code']
        user = User.objects.create_user(**validated_data)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


